package com.controller;

import com.bean.*;
import com.bean.dangBean.Balance;
import com.service.*;
import com.util.PageAssistant;
import com.util.QueryAssistant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 销售模块
 */
@Controller
public class SalesReturnRecordController {

    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private MarketServices marketServices;
    @Autowired
    private CommodityService commodityService;
    @Autowired
    private SalesReturnRecordService salesReturnRecordService;
    @Autowired
    private BalanceService balanceService;

    /**
     * 对某个商品进行退单
     * @param model
     * @param salesReturnRecord
     * @return
     */
    @ResponseBody
    @RequestMapping("salesReturnModify")
    public Map<String, Object> salesReturnModify(Model model,SalesReturnRecord salesReturnRecord){
        System.out.println(">>> salesReturnModify ");
        System.out.println(salesReturnRecord);

        //更改商品订单状态
        ShoppingCart shoppingCart = new ShoppingCart(salesReturnRecord.getOrderId(),salesReturnRecord.getProductId());
        ShoppingCart shoppingCartInfo = shoppingCartService.find(shoppingCart).get(0);
        shoppingCartInfo.setState(1);//设置商品订单状态为退单状态
        shoppingCartService.modify(shoppingCartInfo);

        //判断查询的商品ID存在，查销售价
//        Market market = marketServices.find(new Market(shoppingCart.getProductId())).get(0);
        salesReturnRecord.setPrice(shoppingCartInfo.getUnitPrice()*salesReturnRecord.getNumber());

        //增加退货记录
        salesReturnRecord.setReturnTime(new Date());
        int i = salesReturnRecordService.save(salesReturnRecord);
        //减少超市账户余额
        Map<String, Object> mapBalance = new HashMap<>();
        List<Balance> balanceList = balanceService.query(mapBalance);//查询所有取最近的那一个
        balanceService.save(new Balance(balanceList.get(0).getBalance()-salesReturnRecord.getPrice(),new Date()));//保存余额
        //
        Map<String, Object> map = new HashMap<>();
        if(i == 1){
            map.put("returnState",1);
        }else{
            map.put("returnState",0);
        }
        return map;
    }

    /**
     * 分页查询订单列表
     * @param model
     * @return
     */
    @RequestMapping("searchSalesReturnRecord")
    public String querySalesReturnRecord(Model model, QueryAssistant queryAssistant, PageAssistant<SalesReturnRecord> paSaReturn) throws Exception{
        System.out.println(">>>searchSalesReturnRecord");
        System.out.println(paSaReturn);
        System.out.println(queryAssistant);

        Map<String, Object> map = new HashMap<>();
        //添加查询参数
        Date start =null;
        Date end =null;
        try {
            if(queryAssistant.getStartTime() !=null && !queryAssistant.getStartTime().equals("")) {
                start = new SimpleDateFormat("yyyy-MM-dd").parse(queryAssistant.getStartTime());
            }
            if(queryAssistant.getEndTime() != null && !queryAssistant.getEndTime().equals("")){
                end = new SimpleDateFormat("yyyy-MM-dd").parse(queryAssistant.getEndTime());
                //设置时分秒为23：59：59
                end.setHours(23);
                end.setMinutes(59);
                end.setSeconds(59);
            }
        } catch (ParseException e) {
//            e.printStackTrace();
        }
        if(queryAssistant.getOrderId() != null && queryAssistant.getOrderId() !="" ){
            map.put("orderId", Long.parseLong(queryAssistant.getOrderId()));
        }
        if(queryAssistant.getProductName() != null && queryAssistant.getProductName() != ""){
            //查询出所有商品名称对应的商品id
            Map<String, Object> mapComm = new HashMap<>();
            mapComm.put("name",queryAssistant.getProductName());
            List<Commodity> commodityList = commodityService.query(mapComm);
            if(commodityList.size() != 1){
                //没有此名称商品
                paSaReturn.setCount(0);
                model.addAttribute("paSaReturn",paSaReturn);
                return "salesReturn/salesReturnRecordSearch";
            }else{
//                System.out.println(commodityList.get(0).getId());
                map.put("productId",commodityList.get(0).getId());
            }
        }
        map.put("startTime", start);
        map.put("endTime",end);

        //查询总记录数
        paSaReturn.setCount(salesReturnRecordService.count(map));

        //设置分页参数
        map.put("start", paSaReturn.getStart());
        map.put("size", paSaReturn.getSize());

        //查询当前页内容
        List<SalesReturnRecord> salesReturnRecordList = salesReturnRecordService.query(map);
        for(SalesReturnRecord sa: salesReturnRecordList){
            //根据商品Id查询,查商品名称
            Commodity commodity = commodityService.find(new Commodity(sa.getProductId())).get(0);
            sa.setCommodity(commodity);
        }
        paSaReturn.setItems(salesReturnRecordList);
        model.addAttribute("paSaReturn",paSaReturn);
        return "salesReturn/salesReturnRecordSearch";
    }
}
